<template>
  <div v-if="dialogVisble">
    <el-dialog :title="title" :visible.sync="dialogVisble" :before-close="handleClose" :close-on-click-modal=false
               width="40%">
      <el-form :model="form" label-position="left" label-width="100px" ref="form" :rules="rules">
        <el-form-item label="元素名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" maxlength="50" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="所属模块" prop="moduleId">
          <el-select v-model="chooseName" placeholder="请选择" ref="selectModuleId" style="width: 100%">
            <!-- // 设置一个input框用作模糊搜索选项功能 -->
            <el-input v-model="treeFilter" class="input" placeholder="此处键入关键词搜索查询" prefix-icon="el-icon-search"
                      style="padding: 5px" clearable/>
            <el-option hidden :key="form.moduleId" value="一级菜单" :label="chooseName"></el-option>
            <el-tree
              ref="tree"
              :data="moduleTree"
              :props="defaultProps"
              @node-click="nodeOnclick"
              :filter-node-method="filterNode"
              :default-expand-all="true"
              :expand-on-click-node="false"
              :check-on-click-node="true"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="定位方式" prop="locationType">
          <el-select v-model="form.locationType" placeholder="请选择定位方式">
            <el-option v-for="item in bys" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="表达式" prop="expression">
          <el-input v-model="form.expression" autocomplete="off" maxlength="200"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" autocomplete="off" maxlength="200"
                    show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
export default {
  name: "cuDialog",
  props: {
    dialogVisble: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    editData: {
      type: Object,
      default: {}
    },
  },
  data() {
    let checkModuleId = (rule, value, callback) => {
      if (this.form.moduleId === undefined || this.form.moduleId === "") {
        callback(new Error('moduleId不能为空'));
      } else {
        callback();
      }
    };
    return {
      treeFilter: "",
      chooseName: "",
      defaultProps: {label: "name", children: "children"},
      projectId: window.sessionStorage.getItem("projectId"),
      form: {
        name: "",
        moduleId: "",
        locationType: "",
        expression: "",
        description: ""
      },
      moduleTree: [],
      rules: {
        name: [{required: true, message: '元素名称不能为空', trigger: 'blur'}],
        locationType: [{required: true, message: '定位方式不能为空', trigger: 'change'}],
        expression: [{required: true, message: '表达式不能为空', trigger: 'blur'}],
        moduleId: [
          {required: true, validator: checkModuleId, message: '所属模块不能为空', trigger: 'change'}
        ]
      },
      bys: [
        {label: "xpath", value: "xpath"},
        {label: "id", value: "id"},
        {label: "name", value: "name"},
        {label: "tagName", value: "tagName"},
        {label: "className", value: "className"},
        {label: "cssSelector", value: "cssSelector"},
        {label: "linkText", value: "linkText"},
        {label: "partialLinkText", value: "partialLinkText"},
        {label: "byTitle", value: "byTitle"},
        {label: "byValue", value: "byValue"},
        {label: "withText", value: "withText"},
        {label: "text", value: "text"},
      ],
    }
  },
  methods: {
    changeClearValidate(value) {
      this.$refs['form'].clearValidate(value)
    },
    filterNode(value, data) {
      if (!value) return true
      const filterRes = data.name.indexOf(value) !== -1
      return filterRes
    },
    // 所属客户树形节点单击事件
    nodeOnclick(data) {
      // 配置树形组件点击节点后，设置选择器的值，配置组件的数据
      this.chooseName = data.name
      this.form.moduleId = data.id
      // 选择器执行完成后，使其失去焦点隐藏下拉框效果
      this.$refs.selectModuleId.blur()
    },
    handleClose() {
      this.$emit("closeDialog")
    },
    save() {
      console.log("form", this.form)
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.title === "新建元素") {
            this.form.createUser = this.$store.state.user.userId;
            this.form.projectId = this.projectId;
            this.api({url: "/addElement", method: "post", data: this.form}).then(resp => {
              this.$emit("refreshList");
              this.$message({message: resp, type: 'success'});
            })
          } else {
            this.form.updateUser = this.$store.state.user.userId;
            this.api({url: "/updateElement", method: "put", data: this.form}).then(resp => {
              this.$emit("refreshList");
              this.$message({message: resp, type: 'success'});
            })
          }
        }
      })

    }
  },
  watch: {
    editData() {
      this.form = {...this.editData}
      this.chooseName = this.form.moduleName;
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    dialogVisble() {
      this.moduleTree = JSON.parse(sessionStorage.getItem("moduleTree"));
    },
    // 搜索过滤，监听input搜索框绑定的treeFilter
    treeFilter(val) {
      this.$refs.tree.filter(val)
      // 当搜索框键入值改变时，将该值作为入参执行树形控件的过滤事件filterNode
    }
  }
}
</script>

<style scoped>

</style>
